package org.domain.sigepac.session;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.faces.context.FacesContext;

import org.domain.sigepac.Utils;
import org.domain.sigepac.Entity.Aluno;
import org.domain.sigepac.Entity.DiasFuncionamento;
import org.domain.sigepac.Entity.Turma;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

@Name("frequenciaImpressao")
@Scope(ScopeType.CONVERSATION)
public class FrequenciaImpressao {

	@In(value="#{facesContext}")
	private FacesContext facesContext;

	private Turma turma;
	private Date data = new Date();
	private List<Calendar> dias;

	public void imprimir() throws IOException{

			InputStream inputStream= FrequenciaImpressao.class.getClassLoader().getResourceAsStream("chamada.mht");
			BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));

			StringBuffer str=new StringBuffer();
			while(r.ready()){
				str.append(r.readLine()+"\r\n");
			}
			String modelo=str.toString();
			modelo=modelo.replace("${CORPO}", gerarTabela());
			modelo=modelo.replace("${NOME_TURMA}", turma.getNome());

			Calendar fim=Calendar.getInstance();
			fim.setTime(data);
			fim.set(Calendar.DATE, fim.getMaximum(Calendar.DATE));

			modelo=modelo.replace("${PERIODO}", new SimpleDateFormat("dd/MM/yyyy").format(data)+" - "+ new SimpleDateFormat("dd/MM/yyyy").format(fim.getTime()));

			Utils.download(modelo, facesContext);
	}

	private String gerarTabela(){

		StringBuilder texto= new StringBuilder();
		texto.append("<table class=3DMsoTableGrid border=3D1 cellspacing=3D0 cellpadding=3D0 alig=n=3Dleft style=3D'border-collapse:collapse;border:none;mso-border-alt:solid windowt=ext .5pt; mso-yfti-tbllook:1184;mso-table-lspace:7.05pt;margin-left:4.8pt;mso-table-=rspace: 7.05pt;margin-right:4.8pt;mso-table-anchor-vertical:page;mso-table-anchor-=horizontal: margin;mso-table-left:left;mso-table-top:213.05pt;mso-padding-alt:0cm 5.4p=t 0cm 5.4pt'>");
		List<Aluno> alunos=turma.getAlunosAsList();

		texto.append(gerarTitulo());
		int i=1;
		for(Aluno aluno:alunos){
			texto.append(gerarLinha(aluno,i));
		}
		texto.append("</table>");
		return texto.toString();
	}

	private List<Calendar> getDias(){

		if(dias==null){
			dias=new ArrayList<Calendar>();

			Calendar data= Calendar.getInstance();
			data.setTime(this.data);

			Calendar ini= Calendar.getInstance();

			ini.setTime(this.data);

			ini.set(Calendar.DATE, 1);
			int fim=ini.getMaximum(Calendar.DATE);

			int i;
			List<DiasFuncionamento> diasFuncionamentos=turma.getDiasFuncionamento();
			for(i=1;i<fim;i++){
				Calendar dia=Calendar.getInstance();
				dia.setTime(this.data);
				dia.set(Calendar.DATE, i);
				for(DiasFuncionamento diasFuncionamento:diasFuncionamentos){
					if(dia.get(Calendar.DAY_OF_WEEK)==diasFuncionamento.getPosicao()+1)
						dias.add(dia);

				}
			}
		}
		return dias;
	}


	private String gerarTitulo(){
		StringBuilder texto=new StringBuilder();
		texto.append("<tr style=3D'mso-yfti-irow:0;mso-yfti-firstrow:yes'>   <td width=3D93 valign=3Dtop style=3D'width:69.95pt;border:solid windowtex=t 1.0pt;  mso-border-alt:solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt'>  <p class=3DMsoNormal style=3D'margin-bottom:0cm;margin-bottom:.0001pt;lin=e-height:  normal;mso-element:frame;mso-element-frame-hspace:7.05pt;mso-element-wrap:  around;mso-element-anchor-vertical:page;mso-element-anchor-horizontal:mar=gin;  mso-element-top:213.05pt;mso-height-rule:exactly'><o:p>&nbsp;</o:p></p>  </td>");
		getDias();
		for(Calendar dia: dias){
			texto.append(" <td width=3D93 valign=3Dtop style=3D'width:69.95pt;border:solid windowtex=t 1.0pt;  border-left:none;mso-border-left-alt:solid windowtext .5pt;mso-border-alt:  solid windowtext .5pt;background:#BFBFBF;mso-background-themecolor:backgr=ound1;  mso-background-themeshade:191;padding:0cm 5.4pt 0cm 5.4pt'>  <p class=3DMsoNormal align=3Dcenter style=3D'margin-bottom:0cm;margin-bot=tom:.0001pt;  text-align:center;line-height:normal;mso-element:frame;mso-element-frame-=hspace:  7.05pt;mso-element-wrap:around;mso-element-anchor-vertical:page;mso-eleme=nt-anchor-horizontal:  margin;mso-element-top:213.05pt;mso-height-rule:exactly'><b style=3D'mso-=bidi-font-weight:  normal'>"+new SimpleDateFormat("dd/MM/yyyy").format(dia.getTime())+"<o:p></o:p></b></p>  </td>");
		}
		texto.append("</tr>");
		return texto.toString();
	}

	private String gerarLinha(Aluno aluno,int i){
		StringBuilder texto=new StringBuilder();
		texto.append("<tr style=3D'mso-yfti-irow:"+i+"'>");
		texto.append(gerarColunaAluno(aluno));
		for(Calendar dia: dias){

			texto.append( gerarColuna(turma.isPresente(aluno, dia.getTime())?"X":""));
		}
		texto.append("</tr>");
		return texto.toString();
	}


	private String gerarColunaAluno(Aluno aluno){
		return "  <td width=3D93 valign=3Dtop style=3D'width:69.95pt;border:solid windowtex=t 1.0pt;  border-top:none;mso-border-top-alt:solid windowtext .5pt;mso-border-alt:s=olid windowtext .5pt;  background:#BFBFBF;mso-background-themecolor:background1;mso-background-t=hemeshade:  191;padding:0cm 5.4pt 0cm 5.4pt'>  <p class=3DMsoNormal style=3D'margin-bottom:0cm;margin-bottom:.0001pt;lin=e-height:  normal;mso-element:frame;mso-element-frame-hspace:7.05pt;mso-element-wrap:  around;mso-element-anchor-vertical:page;mso-element-anchor-horizontal:mar=gin;  mso-element-top:213.05pt;mso-height-rule:exactly'><b style=3D'mso-bidi-fo=nt-weight:  normal'>"+aluno.getNome()+"<o:p></o:p></b></p>  </td>";
	}

	private String gerarColuna(String presente){
		return "  <td width=3D93 valign=3Dtop style=3D'width:69.95pt;border-top:none;border=-left:  none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1=.0pt;  mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid window=text .5pt;  mso-border-alt:solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt'>  <p class=3DMsoNormal align=3Dcenter style=3D'margin-bottom:0cm;margin-bot=tom:.0001pt;  text-align:center;line-height:normal;mso-element:frame;mso-element-frame-=hspace:  7.05pt;mso-element-wrap:around;mso-element-anchor-vertical:page;mso-eleme=nt-anchor-horizontal:  margin;mso-element-top:213.05pt;mso-height-rule:exactly'>"+presente+"</p></td>";
	}

	public Turma getTurma() {
		return turma;
	}
	public void setTurma(Turma turma) {
		this.turma = turma;
	}
	public Date getData() {
		return data;
	}
	public void setData(Date data) {
		this.data = data;
	}
}
